package br.com.ruidobrasil.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import br.com.ruidobrasil.negocio.entidade.ImagemPublicacao;
import br.com.ruidobrasil.negocio.entidade.Publicacao;
import br.com.ruidobrasil.negocio.persistencia.dao.ImagemPublicacaoDao;
import br.com.ruidobrasil.negocio.persistencia.dao.PublicacaoDao;
import br.com.ruidobrasil.negocio.persistencia.dao.RuidoBrasilDaoFactory;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PublicacaoDao publicacaoDao = RuidoBrasilDaoFactory.getInstance().criarPublicacaoDao();
		ImagemPublicacaoDao imagemPublicacaoDao = RuidoBrasilDaoFactory.getInstance().criarImagemPublicacaoDao();
		
		Publicacao p = null;
		ImagemPublicacao ip = null;
		
		PrintWriter out = null;
		FileItem item = null;
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ListIterator iterator = null;
		List items = null;
		ServletFileUpload upload = new ServletFileUpload(factory);
		TransformerHandler hd = null;
		
		try {
			out = response.getWriter();
			StreamResult streamResult = new StreamResult(out);
			SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
			
			items = upload.parseRequest(request);
			iterator = items.listIterator();
			
			hd = tf.newTransformerHandler();
			hd.setResult(streamResult);
			hd.startDocument();
			
			while(iterator.hasNext()) {
				
				item = (FileItem)iterator.next();
 
				if(item.isFormField()) {
					
					if (item.getFieldName().equalsIgnoreCase("idPublicacao")) {
						
						// Obtem a publicacao pelo id.
						p = publicacaoDao.obter(Long.parseLong(item.getString()));
						
						ip = new ImagemPublicacao();
						ip.setPublicacao(p);
					}
						
				} else { 
					
					byte[] imagem = IOUtils.toByteArray(item.getInputStream());
					
					if (ip != null) {
						ip.setImagemPublicacao(imagem);
						imagemPublicacaoDao.incluir(ip);
					}
				}
			}
			
			hd.endElement("", "", "response"); 
			hd.endDocument();
			out.close();
						
		} catch (Exception e) { 
			e.printStackTrace();
		}
	}
}
